package com.wd.tw.service;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wd.tw.config.AppConfig;
import com.wd.tw.domain.dto.request.ApiRequest;
import com.wd.tw.domain.dto.request.Basic;
import com.wd.tw.domain.dto.request.LoginRequest;
import com.wd.tw.domain.dto.response.ApiResponse;
import com.wd.tw.domain.dto.response.LoginResponse;
import com.wd.tw.utils.HttpUtils;
import com.wd.tw.utils.Md5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

import static com.wd.tw.constants.ApiConstant.USER_LOGIN;

/**
 * @className: LoginService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/3
 **/
@Service
public class LoginService {

    public static String USER_NAME = "system";
    public static String PASSWORD = "Admin@12345";

    @Resource
    AppConfig appConfig;

    public String getToken() {

        ApiRequest<LoginRequest> loginParam = new ApiRequest<>();

        Basic basic = loginParam.getBasic();
        String pwd = Md5Utils.md5(PASSWORD);

        String rawPwd = basic.getNonce() + "#" +
                basic.getTime() + "#" +
                USER_NAME + "#" + pwd;
        String entryPwd = Md5Utils.md5(rawPwd);

        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUser_name(USER_NAME);
        loginRequest.setPassword(entryPwd);
        loginParam.setData(loginRequest);

        String post = HttpUtils.post(appConfig.getBaseApi() + USER_LOGIN, loginParam.toString());
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ApiResponse<LoginResponse> response = null;
        try {
            response = objectMapper.readValue(post, objectMapper.getTypeFactory().constructParametricType(ApiResponse.class, LoginResponse.class));
            return response.getData().getToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}
